""" mysql初始化
@Project: Rebar
@File: init.py
@Author: hzc
@Date: 2023/3/27 10:51
"""
from fastapi import FastAPI
from config import SUPER_ADMIN, SUPER_ADMIN_PASSWORD, SUPER_ADMIN_COMPANY_ID, SUPER_ADMIN_NICKNAME
# from model.db.mapper import get_user_by_username, add_user, activate_user, add_role, get_role_by_name
from model.db import Tb_Depart
from model.db.mapper import add_admin
# from model.params import UserInfoParam, RoleNameEnum
# from utils import bcrypt_pwd


# def create_role():
#     for role_name, role_rank in zip(RoleNameEnum, RoleRankEnum):
#         try:
#             get_role_by_name(role_name)  # 若角色已存在，则不再创建
#         except Exception as e:
#             role_info = RoleInfoParam(
#                 role_name=role_name,
#                 role_rank=role_rank,
#                 remark=role_name.value
#             )
#             add_role(role_info)
#             # print(e)
from model.db.mapper.company_mapper import add_company
from model.db.mapper.depart_mapper import add_depart, get_depart_by_depart_id
# from model.db.mapper.group_mapper import add_group
from model.db.mapper.users_mapper import add_user
from model.db.mapper.well_mapper import init_core_param
from model.params import CompanyInfoParam
from util import DataNotExist


def mysql_init(app: FastAPI):
    """
    项目启动时创建系统管理员，若存在则不必创建
    :param app:
    :return:
    """

    @app.on_event("startup")
    async def startup_event():
        add_admin()
        # add_group("默认用户组")
        # add_group("默认管理员组")
        init_core_param()
        add_company(CompanyInfoParam( company_name="默认公司", company_code =666, company_representative = "甲",
                                      remark="无备注"))
        try:
            get_depart_by_depart_id('默认部门')
        except DataNotExist:
            add_depart(Tb_Depart(
                depart_name='默认部门',
                company_id=1
            ))

        print("mysql已初始化")
        # try:  # 若系统用户存在但没有激活，直接激活即可
        #     super_admin = get_user_by_username(SUPER_ADMIN)
        #     if not super_admin.is_authorize:
        #         activate_user(super_admin.user_id)
        # except:  # 若没有系统管理员，则直接创建
        #     user_info = UserInfoParam(
        #         nickname=SUPER_ADMIN_NICKNAME,
        #         username=SUPER_ADMIN,
        #         password=SUPER_ADMIN_PASSWORD,
        #         company_id=SUPER_ADMIN_COMPANY_ID,
        #         role_name=RoleNameEnum.Super
        #     )
        #     user = add_user(user_info)
        #     activate_user(user.user_id)
        #     create_role()  # 项目启动时创建角色
